#!/bin/sh
export PATH=/bin:/sbin:/usr/bin:/usr/sbin

mount proc
for p in $(cat /proc/cmdline); do
  case $p in
    barge.switch_root)
      SWITCH_ROOT=true
      ;;
    barge.debug)
      DEBUG=true
      ;;
  esac
done
umount proc

if [ -n "${SWITCH_ROOT}" -a -z "${ROOT_SWITCHED}" ]; then
  if mount -t tmpfs -o size=90% tmpfs /mnt; then
    if tar -C / --exclude=mnt -cf - . | tar -C /mnt/ -xf - ; then
      mkdir /mnt/mnt
      export ROOT_SWITCHED=true
      exec switch_root /mnt /init
    fi
  fi
fi

[ -z "${DEBUG}" ] && set -e

mount -t devtmpfs devtmpfs /dev

mkdir -p /var/log
syslogd
usleep 1000
logger -s -p user.info -t "init[$$]" "Start init"

trap 'logger -s -p user.info -t "init[$$]" "trapped at line ${LINENO}"' ERR

mkdir -p /dev/pts
mkdir -p /dev/shm

logger -s -p user.info -t "init[$$]" "Mounting system"
mount -t devpts devpts /dev/pts
mount -t tmpfs tmpfs /dev/shm
mount -t proc proc /proc
mount -t tmpfs tmpfs /run
mount -t sysfs sysfs /sys

# Create /dev/fd and /dev/std* without udev
ln -sf /proc/self/fd /dev/fd
ln -sf /proc/self/fd/0 /dev/stdin
ln -sf /proc/self/fd/1 /dev/stdout
ln -sf /proc/self/fd/2 /dev/stderr

# Lock the root account
passwd -l root

MOUNT_POINT="/mnt/data"
logger -s -p user.info -t "init[$$]" "Mounting HDD LABEL=BARGE-DATA"
mkdir -p "${MOUNT_POINT}"
if ! mount -t ext4 'LABEL=BARGE-DATA' "${MOUNT_POINT}"; then
  logger -s -p user.info -t "init[$$]" "Running from memory, this won't be good..."
else
  if [ ! -d "${MOUNT_POINT}/home" ]; then
    mv /home "${MOUNT_POINT}/home"
  else
    rm -rf /home
  fi
  ln -s "${MOUNT_POINT}/home" /home

  rm -rf /opt
  mkdir -p "${MOUNT_POINT}/opt"
  ln -s "${MOUNT_POINT}/opt" /opt

  mkdir -p "${MOUNT_POINT}/etc"
  mkdir -p "${MOUNT_POINT}/work/etc"
  mount -t overlay overlay -o lowerdir=/etc,upperdir="${MOUNT_POINT}/etc",workdir="${MOUNT_POINT}/work/etc" /etc

  # for backward compatibility
  OLD_ONE="/mnt/$(grep "${MOUNT_POINT} ext4" /etc/mtab | sed -E 's/^\/dev\/([^ ]*) .*$/\1/g')"
  mkdir -p "${OLD_ONE}"
  mount --bind "${MOUNT_POINT}" "${OLD_ONE}"
fi

logger -s -p user.info -t "init[$$]" "Enabling SWAP LABEL=BARGE-SWAP"
if ! swapon 'LABEL=BARGE-SWAP'; then
  logger -s -p user.info -t "init[$$]" "Could not make swap on LABEL=BARGE-SWAP"
fi

if [ -x /etc/init.d/init.sh ]; then
  logger -s -p user.info -t "init[$$]" "Executing custom configuration in init.sh"
  /etc/init.d/init.sh || true
fi

logger -s -p user.info -t "init[$$]" "Set hostname with /etc/hostname"
/bin/hostname -F /etc/hostname

logger -s -p user.info -t "init[$$]" "Executing ACPId"
/usr/sbin/acpid

logger -s -p user.info -t "init[$$]" "Configuring sysctl"
sysctl -p /etc/sysctl.conf

logger -s -p user.info -t "init[$$]" "Executing startup scripts in /etc/init.d"
/etc/init.d/rcS

if [ -x /etc/init.d/start.sh ]; then
  logger -s -p user.info -t "init[$$]" "Starting custom script start.sh"
  /etc/init.d/start.sh &
fi

sync

logger -s -p user.info -t "init[$$]" "Starting console"
if dmesg | grep -q 'ttyS0 at I/O'; then
  respawn /sbin/getty -L 115200 ttyS0 vt100 &
fi
respawn /sbin/getty 38400 tty0 &
chvt 2

shutdown_trap() {
  local mode=$1

  set +e

  # Send SIGTERM to all processes except pid 1
  killall5 -o $(cat /var/run/acpid.pid)

  # Stop network now
  /etc/init.d/S40network stop

  sync
  # Unmount all at the end
  umount -a -r
  swapoff -a

  sync
  sleep 1
  # Send SIGKILL to all processes except pid 1
  killall5 -9

  case $mode in
    0)
      busybox halt -f
      ;;
    2)
      busybox reboot -f
      ;;
    *)
      busybox poweroff -f
      ;;
  esac
}

trap 'shutdown_trap 0' SIGUSR1        # halt
trap 'shutdown_trap 1' SIGUSR2 SIGPWR # poweroff
trap 'shutdown_trap 2' SIGTERM        # reboot

set -mb
trap '' SIGCHLD
read
